/**
 * 
 */
package com.carnation.qa.socketserver.domain;

import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.List;

import com.carnation.qa.socketserver.common.util.MppContext;

/**
 * @author Nick
 * 
 */
public class Item {

	private final String tabSeparator;

	private int lineNumber;

	private String label = null;

	private Item parent = null;

	private List<Item> children = new ArrayList<Item>();

	/**
	 * @param lineNumber
	 * @param label
	 * @param parent
	 */
	public Item(String tabSeparator, int lineNumber, String label, Item parent) {
		assertNotNull("tabSeparator can't been null.", tabSeparator);
		assertNotNull("labal can't been null.", label);
		this.tabSeparator = tabSeparator;
		this.lineNumber = lineNumber;
		this.label = label;
		this.parent = parent;
	}

	/**
	 * @return the label
	 */
	public String getLabel() {
		return label;
	}

	/**
	 * @return the parent
	 */
	public Item getParent() {
		return parent;
	}

	/**
	 * @return the children
	 */
	public List<Item> getChildren() {
		return children;
	}

	/**
	 * @param item
	 *            add to the children
	 */
	public void addItem(Item item) {
		assertNotNull(item);
		this.children.add(item);
	}

	/**
	 * @return the lineNumber
	 */
	public int getLineNumber() {
		return lineNumber;
	}

	/**
	 * 获取缩进字符串
	 * 
	 * @return the tabSeparator
	 */
	public String getTabSeparator() {
		return tabSeparator;
	}

	public String[] getLabelParts() {
		String[] parts = getLabel().split(tabSeparator);
		return parts;
	}

	/**
	 * 判断当前节点是否是叶子节点
	 * 
	 * @return
	 */
	public boolean isLeaf() {
		return getChildren().isEmpty();
	}

	/**
	 * 判断是否存在叶子节点的子结点
	 * 
	 * @return
	 */
	public boolean hasLeafChild() {
		boolean has = false;
		for (Item i : getChildren()) {
			if ((has = i.isLeaf())) {
				break;
			}
		}
		return has;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(getClass().getName());
		sb.append("@lineNumber=");
		sb.append(getLineNumber());
		iterator(this, sb, 0);
		return sb.toString();
	}

	private void iterator(Item item, StringBuilder sb, int tabs) {
		sb.append(MppContext.getNewlineSeparator());
		sb.append(buildTab(tabs));
		sb.append(item.getLabel());
		for (Item i : item.getChildren()) {
			iterator(i, sb, tabs + 1);
		}
	}

	private String buildTab(int tabs) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < tabs; i++) {
			sb.append(this.tabSeparator);
		}
		return sb.toString();
	}
}
